var v8 = require('v8');
var fs = require('fs');
const vm = require('vm');
const { exit } = require('process');
v8.setFlagsFromString('--no-lazy');
global.SOFTNAME = "阔老板_阔软工作室";
global.SOFTVER = "2021.12.01";
global.SOFTHTTP = "https://www.kuosoft.com/";
global.DIR = global.dir = __dirname+"/";
global.temp = dir+"temp/";
global.TPL = dir+"config/";
global.Controller = dir+"Controller/";
global.WWW = dir+"www";
global.p = console.log;
const argv = process.argv;
var filename = "kuo";
var Action  = argv[2];
if( !filename ){
    console.log("file does not exist");
    exit();
}

if( !Action ){
    console.log("Action does not exist");
    exit();
}

var ActionList = {
    "b":"编译",
    "br":"编译运行",
};

if(!ActionList[Action]){
    console.log("Action does not exist [b r br]");
    exit();
}

var filePath = __dirname+"/"+filename+".js";
var filePath__ = __dirname+"/"+filename+"ServerLess.js";
var jscode = "";

function zimulu(mulu){
    mulu = mulu.replace(/Kuo_/g,'')
    try {
        let files = fs.readdirSync(Controller+mulu);
        var time =[];
        files.forEach(file=>{
           
            if(file.indexOf(".js") > -1){
                var wjian = file.split(".js");
                var neirong = fs.readFileSync(Controller+mulu+"/"+file,"utf-8");
                var neirong_ = neirong.split("\n");
                neirong_.shift();
                neirong_.pop();
                time.push(wjian[0]+":"+(neirong_.join("\n")));
            }else{
                if(file != ".DS_Store" && file.indexOf(".") <= -1){
                    time.push(zimulu(mulu+'/'+file));
                }
            }
        });
        return time.join(",");
    } catch (error) {
        return '';
    }
}

function srccode(){
    var code = "";
    let files = fs.readdirSync(Controller);
    files.forEach(file=>{
        if(file.indexOf(".js") > -1){
           var wjian = file.split(".js");
           var neirong = fs.readFileSync(Controller+file,"utf-8");
            if(neirong.indexOf("module.exports") > -1 ){
                var neirong_ = neirong.split("\n");
                neirong_.pop();
                neirong_.push(`global['`+wjian[0]+`'] = `+wjian[0]+`;`)
                code += neirong_.join("\n")+"\n";
            }else{
                var neirong_ = [];
                var huodex = neirong.split("\n");
                neirong_.push(`var `+wjian[0]+` = {`);

                for(var i =1; i < huodex.length - 1 ; i++){
                    neirong_.push(huodex[i]);
                }

                let zimux = zimulu(wjian[0]);
                if(zimux && zimux != ""){
                    neirong_.push(","+zimux);
                }
                neirong_.push(`}`);
                neirong_.push(`global['`+wjian[0]+`'] = `+wjian[0]+`;`)
                code += neirong_.join("\n") +"\n";
            }
        }
    });
    return code ;
}
try {
    jscode = fs.readFileSync(filePath).toString();
} catch (err) {
    console.log("file does not exist!");
    exit();
}
var codejs = `"use strict";
console.log("`+global.SOFTNAME+` v`+global.SOFTVER+` `+global.SOFTHTTP+`");
global.SOFTNAME = "`+global.SOFTNAME+`";
global.SOFTVER = "`+global.SOFTVER+`";
global.SOFTHTTP = "`+global.SOFTHTTP+`";
global.DIR = global.dir = __dirname+"/";
global.temp = dir+"temp/";
global.TPL = dir+"config/";
global.Controller = dir+"Controller/";
global.WWW = dir+"www";
global.p = console.log;
require(TPL+"KuoSoft.com");
`;
var CODEJS = null;
if(Action == "b" || Action == "br"){
    var js_code = "'use strict';((module,require,__dirname,process,global) =>{try{\n";
    js_code += codejs;
    var srccode_ = srccode();
    js_code += srccode_;
    js_code += jscode;
    js_code +="\n}catch(error){console.log('Error:',error)}})";
    //云部署
    fs.writeFileSync(filePath__,codejs+srccode_+jscode);
    try {
        var script = new vm.Script(js_code, {produceCachedData: true});
        var byte_code = script.cachedData;
        CODEJS = Buffer.from(byte_code).toString('base64');
        console.log("Compiled successfully "+Action);
    } catch (error) {
        console.log("Compiled error "+error);
    }
}

if(Action == "br"){
    let byte_code2 = Buffer.from(CODEJS,'base64');
    script = new vm.Script(' '.repeat(byte_code2.readIntLE(8, 4)), {cachedData: byte_code2});
    var fan = script.runInThisContext();
    fan.apply(module.exports,[module,require,__dirname,process,global]);
    console.log("execution succeed "+Action);
}
var RUN = `var v8 = require('v8');
var fs = require('fs');
const vm = require('vm');
v8.setFlagsFromString('--no-lazy');
var byte_code = Buffer.from(\``+CODEJS+`\`,'base64');
var script = new vm.Script(' '.repeat(byte_code.readIntLE(8, 4)), {cachedData: byte_code});
var fan = script.runInThisContext();
fan.apply(module.exports,[module,require,__dirname,process,global]);
console.log("Compiled successfully ");`;
fs.writeFileSync(__dirname+"/kuo.bin",RUN);